<template>
  <ElDialog
    v-model="visible"
    :title="dialogTitle"
    width="700px"
    top="4vh"
    :close-on-click-modal="false"
    @open="handleOpen"
    @close="handleClose"
  >
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="right">
      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="姓名" prop="newName">
            <ElInput
              v-model="form.newName"
              placeholder="请输入姓名"
              maxlength="30"
              show-word-limit
              :disabled="isView"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="身份证号" prop="newIdentity">
            <ElInput
              v-model="form.newIdentity"
              placeholder="请输入身份证号"
              maxlength="18"
              :disabled="isView"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="所属平台" prop="newPlatform">
            <!-- <ElSelect v-model="form.newPlatform" placeholder="请选择所属平台" :disabled="isView">
              <ElOption label="快递员" :value="10020" />
              <ElOption label="外卖员" :value="10021" />
              <ElOption label="网约车司机" :value="10022" />
              <ElOption label="其他" :value="10023" />
            </ElSelect> -->
            <DictSelect
              v-model="form.newPlatform"
              dict-type="10020"
              placeholder="请选择所属平台"
              clearable
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="认证状态" prop="authStatus">
            <!-- <ElSelect v-model="form.authStatus" placeholder="请选择认证状态" :disabled="isView">
              <ElOption label="待核实" :value="10025" />
              <ElOption label="已核实" :value="10026" />
              <ElOption label="核实失败" :value="10027" />
            </ElSelect> -->
            <DictSelect
              v-model="form.authStatus"
              dict-type="10025"
              placeholder="请选择认证状态"
              clearable
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="handleClose">{{ isView ? '关闭' : '取消' }}</ElButton>
        <ElButton v-if="!isView" type="primary" :loading="loading" @click="handleSubmit">
          确定
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, computed, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { clone } from 'xe-utils'
  import { DictSelect } from '@/components/core/dics/index.vue'
  import {
    openApiNewAuthUserSaveDataUsingPost,
    openApiNewAuthUserUpdateDataUsingPost
  } from '@/api/neWyirenzhengrenyuan'


  // 类型定义
  interface Props {
    modelValue: boolean
    userData?: any | null
    isView?: boolean
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  // Props 和 Emits
  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    userData: undefined,
    isView: false
  })

  const emit = defineEmits<Emits>()

  // 响应式数据
  const formRef = ref<FormInstance>()
  const loading = ref(false)

  const initForm = {
    newName: '',
    newIdentity: '',
    newPlatform: '',
    authStatus: ''
  }

  const form = ref(clone(initForm, true))

  // 计算属性
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  const isEdit = computed(() => !!props.userData?.id)
  const isView = computed(() => props.isView)

  const dialogTitle = computed(() => {
    if (isView.value) return '查看已认证人员'
    return isEdit.value ? '编辑已认证人员' : '新增已认证人员'
  })

  // 身份证号验证函数
  const validateIdCard = (rule: any, value: string, callback: any) => {
    if (!value) {
      callback(new Error('请输入身份证号'))
      return
    }
    const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
    if (!idCardRegex.test(value)) {
      callback(new Error('请输入正确的身份证号'))
      return
    }
    callback()
  }

  // 表单验证规则
  const rules: FormRules = {
    newName: [
      { required: true, message: '请输入姓名', trigger: 'blur' },
      { max: 30, message: '姓名不能超过30个字符', trigger: 'blur' }
    ],
    newIdentity: [{ required: true, validator: validateIdCard, trigger: 'blur' }],
    newPlatform: [{ required: true, message: '请选择所属平台', trigger: 'change' }],
    authStatus: [{ required: true, message: '请选择认证状态', trigger: 'change' }]
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()

      loading.value = true

      if (isEdit.value) {
        // 编辑
        await openApiNewAuthUserUpDataUsingPost({
          body: form.value
        })
      } else {
        // 新增
        await openApiNewAuthUserSaveDataUsingPost({
          body: form.value
        })
      }

      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
      emit('success')
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      loading.value = false
    }
  }

  const handleOpen = () => {
    if (isEdit.value && props.userData) {
      // 编辑/查看模式，回显数据
      nextTick(() => {
        form.value = clone(props.userData, true)
      })
    } else {
      // 新增模式，重置表单
      form.value = clone(initForm, true)
    }
  }

  const handleClose = () => {
    formRef.value?.resetFields()
    nextTick(() => {
      visible.value = false
    })
  }
</script>

<style lang="scss" scoped>
  .dialog-footer {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }
</style>
